<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let eatenApples = function (apples, days) {
      let maxLen = Math.max(...days.map((day, index) => day + index));
      let plan = new Array(maxLen).fill(0);
      let count = 0;
      for (let i = 0; i < plan.length; i++) {
        if (i < apples.length) {
          plan[i + days[i] - 1] += apples[i];
        }
        for (let j = i; j < plan.length; j++) {
          if (plan[j] > 0) {
            plan[j]--;
            count++;
            break;
          }
        }
      }
      return count;
    }
    console.log(eatenApples(apples = [1, 2, 3, 5, 2], days = [3, 2, 1, 4, 2]));
  </script>
</body>

</html>